package com.hs.jhzd.controller;

import java.util.List;
import java.util.Optional;

import com.hs.jhzd.utils.ToolUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hs.jhzd.entity.Dorm;
import com.hs.jhzd.repository.DormRepository;

@Controller
@RequestMapping("/dorm")
public class DormController {

  @Value("${jsbh}")
  private String jsbh;

  @Autowired
  private DormRepository repository;

  @RequestMapping("/findByAreacode")
  @ResponseBody
  public List<Dorm> findByAreacode(String areacode) {
    return repository.findByAreacodeOrderByDormcode(areacode);
  }

  @RequestMapping("/save")
  @ResponseBody
  public void save(Dorm dorm) {
    if(StringUtil.isBlank(dorm.getId())){
      //生成主键--------
      String oldId = repository.findZybh();
      dorm.setId(ToolUtils.CreatePrimaryKey(oldId));
      repository.save(dorm);
    }else {
      repository.updateDorm(dorm.getAreacode(),dorm.getDormcode(),dorm.getDormname(),dorm.getDormtype(),dorm.getId());
    }
  }

  @RequestMapping("/delete")
  @ResponseBody
  public void delete(String id) {
    repository.deleteById(id);
  }

  @RequestMapping("/findById")
  @ResponseBody
  public Dorm findById(String id) {
    Optional<Dorm> dorm = repository.findById(id);
    return dorm.isPresent() ? dorm.get() : null;
  }

  @RequestMapping("/admin/main")
  public String mainPage(Model model) {
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("dorms", repository.findByDormtypeNot("11"));
    return "dorm-list";
  }
}
